import uuid
from decimal import Decimal
from django.db import transaction
from django.core.exceptions import ValidationError
from django.utils import timezone
from .models import Order, OrderItem, Cart, OrderLog
from apps.users.models import UserAddress
from apps.flowers.services import FlowerService


class OrderService:
    """订单服务"""
    
    @staticmethod
    def generate_order_no():
        """生成订单号"""
        import time
        timestamp = str(int(time.time()))
        random_str = str(uuid.uuid4().hex)[:8]
        return f"HXG{timestamp}{random_str}".upper()
    
    @staticmethod
    @transaction.atomic
    def create_order(user_id, cart_ids, address_id, remark=None, delivery_time=None):
        """创建订单"""
        # 获取购物车商品
        cart_items = Cart.objects.filter(
            id__in=cart_ids,
            user_id=user_id
        ).select_related('flower', 'flower_spec')
        
        if not cart_items.exists():
            raise ValidationError("购物车商品不存在")
        
        # 获取收货地址
        try:
            address = UserAddress.objects.get(id=address_id, user_id=user_id)
        except UserAddress.DoesNotExist:
            raise ValidationError("收货地址不存在")
        
        # 检查库存并计算总价
        total_amount = Decimal('0')
        order_items_data = []
        
        for cart_item in cart_items:
            flower = cart_item.flower
            flower_spec = cart_item.flower_spec
            quantity = cart_item.quantity
            
            # 检查商品状态
            if flower.status != 'active':
                raise ValidationError(f"商品 {flower.name} 已下架")
            
            # 检查库存
            if flower_spec:
                if flower_spec.stock < quantity:
                    raise ValidationError(f"商品 {flower.name} 规格 {flower_spec.name} 库存不足")
                unit_price = flower_spec.price
            else:
                if flower.stock < quantity:
                    raise ValidationError(f"商品 {flower.name} 库存不足")
                unit_price = flower.price
            
            item_total = unit_price * quantity
            total_amount += item_total
            
            order_items_data.append({
                'flower': flower,
                'flower_spec': flower_spec,
                'flower_name': flower.name,
                'flower_image': flower.main_image,
                'spec_name': flower_spec.name if flower_spec else None,
                'unit_price': unit_price,
                'quantity': quantity,
                'total_price': item_total
            })
        
        # 计算运费（简化处理，固定运费）
        shipping_fee = Decimal('10.00') if total_amount < 100 else Decimal('0')
        actual_amount = total_amount + shipping_fee
        
        # 创建订单
        order = Order.objects.create(
            order_no=OrderService.generate_order_no(),
            user_id=user_id,
            receiver_name=address.name,
            receiver_phone=address.phone,
            receiver_address=address.full_address,
            total_amount=total_amount,
            shipping_fee=shipping_fee,
            actual_amount=actual_amount,
            remark=remark,
            delivery_time=delivery_time
        )
        
        # 创建订单商品
        for item_data in order_items_data:
            OrderItem.objects.create(order=order, **item_data)
        
        # 扣减库存
        for cart_item in cart_items:
            if cart_item.flower_spec:
                FlowerService.update_stock(
                    cart_item.flower.id, 
                    cart_item.quantity, 
                    'decrease'
                )
            else:
                FlowerService.update_stock(
                    cart_item.flower.id, 
                    cart_item.quantity, 
                    'decrease'
                )
        
        # 清空购物车
        cart_items.delete()
        
        # 记录日志
        OrderLogService.create_log(order.id, 'create', '订单创建', f'用户{user_id}')
        
        return order
    
    @staticmethod
    def get_user_orders(user_id, status=None):
        """获取用户订单列表"""
        queryset = Order.objects.filter(user_id=user_id)
        if status:
            queryset = queryset.filter(status=status)
        return queryset.order_by('-created_at')
    
    @staticmethod
    def get_order_detail(order_id, user_id=None):
        """获取订单详情"""
        try:
            queryset = Order.objects.select_related('user').prefetch_related('items')
            if user_id:
                queryset = queryset.filter(user_id=user_id)
            return queryset.get(id=order_id)
        except Order.DoesNotExist:
            raise ValidationError("订单不存在")
    
    @staticmethod
    @transaction.atomic
    def cancel_order(order_id, user_id, reason="用户取消"):
        """取消订单"""
        order = OrderService.get_order_detail(order_id, user_id)
        
        if order.status not in ['pending', 'paid']:
            raise ValidationError("当前订单状态不允许取消")
        
        # 恢复库存
        for item in order.items.all():
            if item.flower_spec:
                FlowerService.update_stock(
                    item.flower.id,
                    item.quantity,
                    'increase'
                )
            else:
                FlowerService.update_stock(
                    item.flower.id,
                    item.quantity,
                    'increase'
                )
        
        # 更新订单状态
        order.status = 'cancelled'
        order.save()
        
        # 记录日志
        OrderLogService.create_log(order.id, 'cancel', reason, f'用户{user_id}')
        
        return order
    
    @staticmethod
    def confirm_receipt(order_id, user_id):
        """确认收货"""
        order = OrderService.get_order_detail(order_id, user_id)
        
        if order.status != 'delivered':
            raise ValidationError("订单未送达，无法确认收货")
        
        order.status = 'completed'
        order.save()
        
        # 更新销售数量
        for item in order.items.all():
            FlowerService.update_sales_count(item.flower.id, item.quantity)
        
        # 记录日志
        OrderLogService.create_log(order.id, 'confirm', '确认收货', f'用户{user_id}')
        
        return order


class CartService:
    """购物车服务"""
    
    @staticmethod
    def get_user_cart(user_id):
        """获取用户购物车"""
        return Cart.objects.filter(user_id=user_id).select_related(
            'flower', 'flower_spec'
        ).order_by('-created_at')
    
    @staticmethod
    def add_to_cart(user_id, flower_id, flower_spec_id=None, quantity=1):
        """添加到购物车"""
        # 检查是否已存在
        cart_item, created = Cart.objects.get_or_create(
            user_id=user_id,
            flower_id=flower_id,
            flower_spec_id=flower_spec_id,
            defaults={'quantity': quantity}
        )
        
        if not created:
            # 如果已存在，增加数量
            cart_item.quantity += quantity
            cart_item.save()
        
        return cart_item
    
    @staticmethod
    def update_cart_quantity(cart_id, user_id, quantity):
        """更新购物车商品数量"""
        try:
            cart_item = Cart.objects.get(id=cart_id, user_id=user_id)
            cart_item.quantity = quantity
            cart_item.save()
            return cart_item
        except Cart.DoesNotExist:
            raise ValidationError("购物车商品不存在")
    
    @staticmethod
    def remove_from_cart(cart_id, user_id):
        """从购物车移除商品"""
        try:
            cart_item = Cart.objects.get(id=cart_id, user_id=user_id)
            cart_item.delete()
        except Cart.DoesNotExist:
            raise ValidationError("购物车商品不存在")
    
    @staticmethod
    def clear_cart(user_id):
        """清空购物车"""
        Cart.objects.filter(user_id=user_id).delete()
    
    @staticmethod
    def get_cart_total(user_id):
        """获取购物车总价"""
        cart_items = Cart.objects.filter(user_id=user_id).select_related(
            'flower', 'flower_spec'
        )
        
        total_amount = Decimal('0')
        total_count = 0
        
        for item in cart_items:
            if item.flower_spec:
                price = item.flower_spec.price
            else:
                price = item.flower.price
            
            total_amount += price * item.quantity
            total_count += item.quantity
        
        return {
            'total_amount': total_amount,
            'total_count': total_count
        }


class PaymentService:
    """支付服务"""
    
    @staticmethod
    def create_payment(order_id, payment_method):
        """创建支付"""
        try:
            order = Order.objects.get(id=order_id)
            if order.status != 'pending':
                raise ValidationError("订单状态不允许支付")
            
            # 这里应该调用实际的支付接口
            # 简化处理，直接返回支付参数
            payment_params = {
                'order_no': order.order_no,
                'amount': str(order.actual_amount),
                'payment_method': payment_method,
                'timestamp': int(timezone.now().timestamp())
            }
            
            return payment_params
        except Order.DoesNotExist:
            raise ValidationError("订单不存在")
    
    @staticmethod
    @transaction.atomic
    def handle_payment_success(order_no, transaction_id, payment_method):
        """处理支付成功"""
        try:
            order = Order.objects.get(order_no=order_no)
            order.status = 'paid'
            order.payment_method = payment_method
            order.payment_time = timezone.now()
            order.transaction_id = transaction_id
            order.save()
            
            # 记录日志
            OrderLogService.create_log(order.id, 'pay', '支付成功', 'system')
            
            return order
        except Order.DoesNotExist:
            raise ValidationError("订单不存在")


class OrderLogService:
    """订单日志服务"""
    
    @staticmethod
    def create_log(order_id, action, description, operator=None):
        """创建订单日志"""
        return OrderLog.objects.create(
            order_id=order_id,
            action=action,
            description=description,
            operator=operator
        )
    
    @staticmethod
    def get_order_logs(order_id):
        """获取订单日志"""
        return OrderLog.objects.filter(order_id=order_id).order_by('-created_at')


class OrderStatisticsService:
    """订单统计服务"""
    
    @staticmethod
    def get_user_order_stats(user_id):
        """获取用户订单统计"""
        from django.db.models import Count, Sum, Q
        
        orders = Order.objects.filter(user_id=user_id)
        
        stats = orders.aggregate(
            total_orders=Count('id'),
            total_amount=Sum('actual_amount'),
            pending_count=Count('id', filter=Q(status='pending')),
            paid_count=Count('id', filter=Q(status='paid')),
            shipped_count=Count('id', filter=Q(status='shipped')),
            completed_count=Count('id', filter=Q(status='completed'))
        )
        
        return stats
